package org.koyad.portal.filters;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.koyad.portal.context.PistonContext;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.misc.FilterPreProcessor;
import org.koyad.portal.tags.ViewRoot;
import org.koyad.portal.utils.LogUtils;
import org.koyad.portal.vo.PageMetaData;

@WebFilter (
		filterName = "NormalPageFilter", 
		urlPatterns = {
			"*.page"
		}
)
public class NormalPageFilter extends BaseFilter {

	private static final LogUtils LOGGER = LogUtils.getLogger(NormalPageFilter.class);

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		
		LOGGER.startMethod("doFilter");
		
		HttpServletRequest httpReq = (HttpServletRequest)req;
		HttpServletResponse httpResp = (HttpServletResponse)resp;
		
		try {
			
			super.doFilter(req, resp, chain);
			
			String _uri = httpReq.getRequestURI();
			int beginIndex = _uri.indexOf('/', 1);
			int endIndex = _uri.indexOf(".page");
			String pageURI = _uri.substring(beginIndex, endIndex);
			pageURI = pageURI + ".xml";
			
			PageMetaData page = new PageMetaData(null, pageURI);
				
			ViewRoot viewRoot = PistonContext.getContext().getViewRoot();
			if(null == viewRoot || !viewRoot.getMetaData().equals(page)) {
				LOGGER.info("Creating view tree for normal page -> " + page.getPath());
				
				InputStream is = req.getServletContext().getResourceAsStream(page.getPath());
				
				if(null != is) {
					PageUtils.createViewRoot(page);
					chain.doFilter(req, resp);
				} else {
					PageUtils.include("/NotFound.html", httpReq, httpResp);
				}
			}
		} catch (FrameworkException e) {
			LOGGER.logException(e);
			PageUtils.include("/Error.html", httpReq, httpResp);
		}
		
		chain.doFilter(req, resp);
		
		LOGGER.endMethod("doFilter");

	}

}
